package main

import (
	"encoding/json"
	"log"
	"net/http"
)

type User struct {
	ID       int    `json:"id"`
	Username string `json:"username"`
	Email    string `json:"email"`
}

var users []User

func main() {
	// 设置路由处理函数
	http.HandleFunc("/users", getUsersHandler)
	http.HandleFunc("/users/add", addUserHandler)

	// 启动服务器
	log.Println("Server started on http://localhost:8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

// 处理获取用户列表请求
func getUsersHandler(w http.ResponseWriter, r *http.Request) {
	// 设置响应头
	w.Header().Set("Content-Type", "application/json")

	// 将用户列表转换为JSON
	usersJSON, err := json.Marshal(users)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// 写入响应
	w.WriteHeader(http.StatusOK)
	w.Write(usersJSON)
}

// 处理添加用户请求
func addUserHandler(w http.ResponseWriter, r *http.Request) {
	// 解析请求体中的JSON数据
	var newUser User
	err := json.NewDecoder(r.Body).Decode(&newUser)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// 将新用户添加到用户列表
	users = append(users, newUser)

	// 设置响应头
	w.Header().Set("Content-Type", "application/json")

	// 返回成功状态
	w.WriteHeader(http.StatusCreated)
}

